﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.SharePoint.Client;
using SPClientAdmin.Core.Common.Exceptions;

namespace SPClientAdmin.Core
{
    public class ClientAccessManager : IDisposable
    {
        protected ClientContext Context = null;
        public bool IsClientAccessOpened { get { return Context != null; } }


        public ClientAccessManager(string url)
        {
            ConnectToServer(url);
        }

        protected void ConnectToServer(string url)
        {
            ConnectToServer(url, CredentialCache.DefaultNetworkCredentials);
        }

        protected void ConnectToServer(string url, string login, string password)
        {
            ConnectToServer(url, new NetworkCredential(login, password));
        }

        protected void ConnectToServer(string url, NetworkCredential credential)
        {
            try
            {
                Context = new ClientContext(url);
                Context.Credentials = credential;
                Context.Load(Context.Web, w => w.Title);
                Context.ExecuteQuery();
            }
            catch (WebException)
            {
                throw new UnableToConnectException(url);
            }
        }

        public void Dispose()
        {
            if (IsClientAccessOpened)
            {
                Context.Dispose();
            }
        }
    }
}
